import React, { useMemo, useState, useEffect, useRef } from 'react';
import { useLocation } from 'dva';
import styles from './indexDetail.less';
// import 'swiper/swiper-bundle.css'
import NewSwiper from './NewSwiper';
import ProductsCard from '../../components/productsCard';
import bicycle1 from '../../assets/index/bicycle1.jpg';
import bicycle2 from '../../assets/index/bicycle2.jpg';
import HomeOverlay from '../../components/homeOverlay';
import introIcon from '../../assets/index/intro.png';
import otherIcon from '../../assets/index/other.png';
import defaultLogo from '../../assets/index/logo.png';
import companyIcon from '../../assets/index/company.png';
import DetailBar from '../../components/detailBar';
import Enquiry from './Enquiry/enquiry';
import NewModal from '../../components/newModal';
import { useParams, useDispatch, useSelector, useHistory } from 'dva';
import { GetImgs } from '../../utils/tools';
import { E } from '../../../../constants';
import { getLocale } from 'umi';
import { useIntl } from 'umi';
import { Toast } from 'antd-mobile';

import FloatButton from '../../components/FloatButton/index';

import { getShareImage } from '../../servers/service';

import IconShare from '../../assets/icon/ic_schb@2x.png';

import { Currency } from '../../utils/utils';

function Index() {
  const { id } = useParams();
  const box = useRef();
  const dispatch = useDispatch();
  const history = useHistory();
  const { productDetail, exProduct, userInfo } = useSelector(({ index }) => index);
  const [isShowModal, setIsShowModal] = useState(false);
  const intl = useIntl();

  const [shareVisible, setShareVisible] = useState(false);
  const [shareUrl, setShareUrl] = useState();

  const [shareParams, setShareParams] = useState();

  const barConfig = [
    {
      title: intl.formatMessage({ id: 'COLLECT' }),
      value: productDetail && productDetail.collectCount,
      callback: () => {
        if (!userInfo) {
          dispatch({
            type: 'index/setState',
            payload: {
              loginModalShow: true,
            },
          });
          return;
        }
        dispatch({
          type: 'index/apiPostLikeProduct',
          payload: {
            objectId: id,
            objectType: 'EXHIBIT',
            type: 'COLLECTED',
            userId: userInfo?.user?.id,
          },
          callback: () => {
            dispatch({
              type: 'index/apiGetProductDetail',
              payload: { id },
            });
          },
        });
      },
    },
    {
      title: intl.formatMessage({ id: 'INQUIRY' }),
      value: productDetail && productDetail.enquiryCount,
      callback: () => {
        // alert('aaaa')
        if (!userInfo) {
          dispatch({
            type: 'index/setState',
            payload: {
              loginModalShow: true,
            },
          });
          return;
        }
        setIsShowModal(true);
      },
    },
  ];

  useEffect(() => {
    // console.log(id)
    if (id) {
      dispatch({
        type: 'index/apiGetProductDetail',
        payload: { id },
      });
    }
  }, [id]);

  useEffect(() => {
    if (productDetail) {
      dispatch({
        type: 'index/apiGetExProducts',
        payload: { exhibitorId: productDetail?.exhibitor?.id },
      });
      const baseUrl = `${window.location.origin}/#`;
      const params = {
        productBannerUrl: Array.isArray(productDetail?.properties?.albums)
          ? productDetail.properties.albums[0]
          : null,
        productUrl: `${baseUrl}/index/details/${productDetail.id}`,
        productName: getLocale() == 'zh-CN' ? productDetail.name : productDetail.nameEn,
        categories:
          getLocale() == 'zh-CN' ? productDetail.categoryName : productDetail?.categoryEnName,
        companyLogo: productDetail?.exhibitor?.properties?.logo,
        companyName:
          getLocale() == 'zh-CN' ? productDetail.exhibitor?.name : productDetail.exhibitor?.nameEn,
        companyUrl: `${baseUrl}/index/exhibitorDetail/${productDetail?.exhibitor?.id}`,
        homeUrl: baseUrl,
        boothNumber:
          productDetail.exhibitor?.boothNumber === null ||
          productDetail.exhibitor?.boothNumber === undefined ||
          productDetail.exhibitor?.boothNumber === ''
            ? ''
            : productDetail.exhibitor?.boothNumber,
      };

      setShareParams(params);
    }
    // alert('aaa')
    // box.current
    document.body.scrollTop = document.documentElement.scrollTop = 0;
  }, [productDetail]);

  function getSwiperList() {
    if (productDetail) {
      if (productDetail.properties) {
        return productDetail.properties.albums;
      }
      return [];
    }
    return [];
  }
  function getListInfo() {
    let da = [
      {
        title: intl.formatMessage({ id: 'CARLOAD' }),
        text: 'TCR ADVANCED PRO 0 DISC',
        children: <span className={styles.infoItemPrice}>$34800 ~ $34800</span>,
      },
      {
        title: intl.formatMessage({ id: 'TYPE' }),
        text: 'TCR ADVANCED PRO 0 DISC',
      },
      {
        title: intl.formatMessage({ id: 'SIZE' }),
        text: intl.formatMessage({ id: 'CARRIAGE' }),
      },
      {
        title: intl.formatMessage({ id: 'TEXTURE' }),
        text: intl.formatMessage({ id: 'CARBON_FIBER' }),
      },
      {
        title: intl.formatMessage({ id: 'COLOUR' }),
        text: intl.formatMessage({ id: 'BLACK' }),
      },
    ];
    if (productDetail) {
      da[0].text = getLocale() == 'zh-CN' ? productDetail.name : productDetail.nameEn;
      da[0].children = (
        <span className={styles.infoItemPrice}>
          {Currency[productDetail?.currency]?.description}
          {productDetail?.minimum} ~ {Currency[productDetail?.currency]?.description}
          {productDetail?.maximum}
        </span>
      );
      da[1].text = getLocale() == 'zh-CN' ? productDetail.model : productDetail.modelEn;
      da[2].text = getLocale() == 'zh-CN' ? productDetail.exhibitSize : productDetail.exhibitSizeEn;
      da[3].text = getLocale() == 'zh-CN' ? productDetail.material : productDetail.materialEn;
      da[4].text = getLocale() == 'zh-CN' ? productDetail.color : productDetail.colorEn;
    }
    return da;
  }
  function getIntro() {
    if (productDetail) {
      return [getLocale() == 'zh-CN' ? productDetail.description : productDetail.descriptionEn];
    } else {
      return [''];
    }
  }
  function getCompanyInfo() {
    let obj = {
      logo: '',
      name: '',
    };
    if (productDetail) {
      obj.logo = productDetail?.exhibitor && productDetail?.exhibitor?.properties?.logo;
      obj.name =
        getLocale() == 'zh-CN' ? productDetail?.exhibitor?.name : productDetail?.exhibitor?.nameEn;
    }
    return obj;
  }

  function getProducts() {}

  function onOver() {
    setIsShowModal(false);
  }
  function handelGoToExhibitor() {
    history.push(`/index/exhibitorDetail/${productDetail.exhibitor?.id}`);
  }

  const location = useLocation();
  // console.log(userInfo, 'userInfo')
  const list = getSwiperList();
  const listInfo = getListInfo();
  const intro = getIntro();
  const companyInfo = getCompanyInfo();
  // const products = productDetail

  const onShare = async () => {
    if (shareUrl) {
      setShareVisible(true);
      return;
    }
    try {
      Toast.loading('海报生成中', 0, () => {}, true);
      const baseUrl = `${window.location.origin}/#`;
      const params = {
        productBannerUrl: Array.isArray(productDetail?.properties?.albums)
          ? productDetail.properties.albums[0]
          : null,
        productUrl: `${baseUrl}/index/details/${productDetail.id}`,
        productName: getLocale() == 'zh-CN' ? productDetail.name : productDetail.nameEn,
        categories:
          getLocale() == 'zh-CN' ? productDetail.categoryName : productDetail.categoryEnName,
        companyLogo: productDetail?.exhibitor && productDetail?.exhibitor?.properties?.logo,
        companyName:
          getLocale() == 'zh-CN' ? productDetail.exhibitor?.name : productDetail.exhibitor?.nameEn,
        companyUrl: `${baseUrl}/index/exhibitorDetail/${productDetail.exhibitor?.id}`,
        homeUrl: baseUrl,
      };
      const res = await getShareImage('web/share-image/product', params);
      setShareVisible(true);
      setShareUrl(res.url);
      Toast.hide();
    } catch (error) {
      Toast.hide();
    }
  };

  const onSaveShare = async () => {
    alert();
  };

  return (
    <div
      className={styles.page}
      ref={box}
      style={{
        position: 'relative',
      }}
    >
      <FloatButton params={shareParams} url="web/share-image/product" />
      <>
        {shareVisible && (
          <div className={styles.share}>
            <div
              className={styles.mask}
              onClick={() => {
                setShareVisible(false);
              }}
            ></div>
            <div className={styles.shareBox}>
              <img src={shareUrl} className={styles.shareImage} />
              {/* <div className={styles.shareSave} onClick={onSaveShare}>
            保存图片
          </div> */}
            </div>
          </div>
        )}
      </>
      <HomeOverlay />
      <NewSwiper data={list.length > 6 ? list.slice(0, 6) : list} />
      {/* <div
        style={{
          position: 'fixed',
          zIndex: 999,
          right: 20,
          bottom: 120,
        }}
        onClick={onShare}
      >
        <img
          src={IconShare}
          style={{
            width: 65,
            height: 65,
          }}
        />
      </div> */}
      <div className={styles.bicycleInfo}>
        {listInfo.map((item, index) => {
          return (
            <div
              className={styles.infoItem}
              key={`item${index}`}
              style={{ width: index == 0 ? '100%' : '50%' }}
            >
              <span className={styles.title}>{item.title}</span>
              <p className={styles.text}>{item.text}</p>
              {item.children && item.children}
            </div>
          );
        })}
      </div>
      <div className={styles.productIntro}>
        <div className={styles.iconBox}>
          <img src={introIcon} className={styles.introIcon}></img>
          <span>{intl.formatMessage({ id: 'PRODUCT_BRIEF_INTRODUCTION' })}</span>
        </div>
        <div className={styles.textBox}>
          {intro.map((item, index) => {
            return (
              <p
                className={styles.introText}
                key={index}
                dangerouslySetInnerHTML={{ __html: item }}
              >
                {/* {item} */}
              </p>
            );
          })}
        </div>
      </div>
      <div className={styles.otherProducts}>
        <div className={styles.iconBox}>
          <img src={otherIcon} className={styles.otherIcon}></img>
          <span>{intl.formatMessage({ id: 'MISCELLANEOUS_PRODUCTS' })}</span>
        </div>
        <div className={styles.productsBox}>
          {exProduct &&
            exProduct.map((item, index) => {
              return <ProductsCard obj={item} key={index} />;
            })}
          {exProduct && exProduct.length % 2 != 0 && <div className={styles.emptyLabel}></div>}
        </div>
      </div>
      <div className={styles.companyInfo} onClick={handelGoToExhibitor}>
        <div className={styles.iconBox}>
          <img src={companyIcon} className={styles.companyIcon}></img>
          <img src={companyInfo.logo} className={styles.defaultLogo}></img>
          <p>{companyInfo.name}</p>
        </div>
      </div>

      <DetailBar barConfig={barConfig} />
      <NewModal showModal={isShowModal}>
        <Enquiry
          type="2"
          exhibitorID={productDetail && productDetail?.exhibitor?.id}
          productID={id}
          onOver={onOver}
          onClose={onOver}
        />
      </NewModal>
    </div>
  );
}

export default Index;
